//
//  BlackjackGameViewController.m
//  Blackjack
//
//  Created by mrbradle on 11/7/11.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "BlackjackGameViewController.h"

#import "BlackjackGame.h"

@implementation BlackjackGameViewController

@synthesize game,houseLabel,playerLabel,betLabel,roundLabel,chipsLabel,deckCards,houseCards,playerCards;
@synthesize betSlider,minBetLabel,maxBetLabel,currentBetLabel,dealButton;
@synthesize hitButton,standButton,doubleButton,splitButton,continueButton,valueLabel,houseValueLabel;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)initGame:(BlackjackGame*)game_ {
    
    //NSLog(@"cCheckpoint 3.1");
    self.game = game_;
    [self updateView];
    
}

- (void)updateView {
    
    //NSLog(@"CHECKPOINT 3.5");
    
    self.houseLabel.text = @"House";
    
    //self.playerLabel.text = game.name;
    self.playerLabel.text = game.name;
    
    self.betLabel.text = [NSString stringWithFormat:@"Bet: %d",game.currentBet];
    self.roundLabel.text = [NSString stringWithFormat:@"Rounds: %d/%d",game.currentRound,game.rounds];
    self.chipsLabel.text = [NSString stringWithFormat:@"Chips: %d",game.currentChips];
    
    //Hide views based on game status
    self.minBetLabel.hidden = (game.status != 1);
    self.maxBetLabel.hidden = (game.status != 1);
    self.currentBetLabel.hidden = (game.status != 1);
    self.betSlider.hidden = (game.status != 1);
    self.dealButton.hidden = (game.status != 1);
    
    self.hitButton.hidden = (game.status != 2 && game.status != 3);
    self.standButton.hidden = (game.status != 2 && game.status != 3);
    self.doubleButton.hidden = (game.status != 2 && game.status != 3);
    self.splitButton.hidden = (game.status != 2 && game.status != 3);
    self.valueLabel.hidden = (game.status != 2 && game.status != 3 && game.status != 4);
    self.houseValueLabel.hidden = (game.status != 2 && game.status != 3 && game.status != 4);

    self.continueButton.hidden = (game.status != 4);
    
    self.doubleButton.enabled = (game.currentPlayerCards == 2); //Only available on first choice
    /*int tempValue1 = game.playerCards[0] % 13;
    if (tempValue1 > 10) tempValue1 = 10;
    if (tempValue1 == 1) tempValue1 = 11;
    int tempValue2 = game.playerCards[1] % 13;
    if (tempValue2 > 10) tempValue2 = 10;
    if (tempValue2 == 1) tempValue2 = 11;
    
    self.splitButton.enabled = (tempValue1 == tempValue2);*/
    self.splitButton.enabled = NO;
    
    if (game.status == 1) {
        minBetLabel.text = [NSString stringWithFormat:@"%d",game.minBet];
        maxBetLabel.text = [NSString stringWithFormat:@"%d",game.currentMaxBet];
        betSlider.value = 0.49;
        game.currentBet = betSlider.value*(game.currentMaxBet-1)+game.minBet;
        currentBetLabel.text = [NSString stringWithFormat:@"Bet: %d",game.currentBet];
    } else if (game.status == 2 || game.status == 3) {
        //Here we find the value of the player's hand and update our label.
        
        int value;
        value = game.playerValue;
        
        //Three cases: player's hand is under 21 and an ace (display two numbers)
        //Player's hand is over 21 with an ace
        //Player's hand is under 21 with no ace
        
        if (game.playerHasAce)
            if (value > 21) self.valueLabel.text = [NSString stringWithFormat:@"%d",value-10];
            else self.valueLabel.text = [NSString stringWithFormat:@"%d/%d",value-10,value];
        else
            self.valueLabel.text = [NSString stringWithFormat:@"%d",value];
        
        //Repeat for the house
        //We do two different things based on the status.  We display the full value when it's the house's turn, otherwise
        //just the value of the first card.
        
        value = game.houseValue;
        
        if (game.houseHasAce)
            if (value > 21) self.houseValueLabel.text = [NSString stringWithFormat:@"%d",value-10];
            else self.houseValueLabel.text = [NSString stringWithFormat:@"%d/%d",value-10,value];
        else
            self.houseValueLabel.text = [NSString stringWithFormat:@"%d",value];

    
    }
    
}

//Updates the x-positions of the player cards.
- (void)updatePlayerCards {
    //The center of the screen is at 160.  The width of the card is 36.  There should be 4 pixels in between cards.
    //For game.currentPlayerCards <= 5, we have no overlaps.  We will determine the left-most position and display
    //all cards in a row.
    
    int leftPos = 142-20*(game.currentPlayerCards-1);
    //NSLog(@"Checkpoint 10");
    for (int i = 0; i < game.currentPlayerCards; i++) {
        [[self.playerCards objectAtIndex:i] setFrame:CGRectMake(leftPos+40*i, 200, 36, 48)];
    }
    
}

- (void)updateHouseCards {
    int leftPos = 142-20*(game.currentHouseCards-1);
    for (int i = 0; i < game.currentHouseCards; i++) {
        [[self.houseCards objectAtIndex:i] setFrame:CGRectMake(leftPos+40*i, 48, 36, 48)];
    }
}

- (void)startGame {
    
    //Start the game.  All data related to the blackjack game will be done here.
    
    [game newGame];
    
    //Put a few face-down cards to represent the deck of cards
    
    for (int k = 0; k < 6; k++) {
        UIImageView* i = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"b2fv"]];
        [i setFrame:CGRectMake(280-k, 60-k, 36, 48)];
        [self.view addSubview:i];
        [deckCards addObject:i];
    }
    
    [self updateView];
        
}

- (IBAction)currentBetChanged {
    game.currentBet = betSlider.value*(game.currentMaxBet-1)+game.minBet;
    currentBetLabel.text = [NSString stringWithFormat:@"Bet: %d",game.currentBet];
}

- (IBAction)deal {
    
    [game deal];
    
    [self updateView];
    
    self.playerCards = [NSMutableArray arrayWithCapacity:13];
    self.houseCards = [NSMutableArray arrayWithCapacity:13];
    
    //Now we have to place the player and house hands.

    for (int i = 0; i < game.currentPlayerCards; i++) {
        UIImageView* v = [[UIImageView alloc] initWithImage:[UIImage imageNamed:
                                                                [NSString stringWithFormat:@"%d",
                                                                game.playerCards[i]+1]]];
        [self.playerCards addObject:v];
        [self.view addSubview:v];
    }
    
    for (int i = 0; i < game.currentHouseCards; i++) {
        UIImageView* v = [[UIImageView alloc] initWithImage:[UIImage imageNamed:
                                                             [NSString stringWithFormat:@"%d",
                                                              game.houseCards[i]+1]]];
        if (i == 0) v.image = [UIImage imageNamed:@"b2fv"];
        [self.houseCards addObject:v];
        [self.view addSubview:v];
    }    
    
    //Call these methods to place the cards in the right positions
    [self updatePlayerCards];
    [self updateHouseCards];
}

- (void)bust {
    
    [game bust];
    
    UIImageView* v = [self.houseCards objectAtIndex:0];
    v.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",game.houseCards[0]+1]];
    
    [self updateHouseCards];
    [self updateView];
    
    [self endRound];
    
}

- (IBAction)hit {
    
    [game hit];
    UIImageView* v = [[UIImageView alloc] initWithImage:[UIImage imageNamed:
                                                         [NSString stringWithFormat:@"%d",
                                                          game.playerCards[game.currentPlayerCards-1]+1]]];
    //NSLog(@"%d",game.playerCards[game.currentPlayerCards-1]);
    [self.playerCards addObject:v];
    [self.view addSubview:v];
    [self updatePlayerCards];
    [self updateView];
    
    //Check if we've busted.  If we have we can't go any farther.
    if (game.playerValue > 21) [self bust];
        
}

- (IBAction)stand {
    
    [game stand];
    
    [game playHouse];
    
    UIImageView* v = [self.houseCards objectAtIndex:0];
    v.image = [UIImage imageNamed:[NSString stringWithFormat:@"%d",game.houseCards[0]+1]];
    for (int i = 2; i < game.currentHouseCards; i++) {
        UIImageView* w = [[UIImageView alloc] initWithImage:[UIImage imageNamed:
                                                             [NSString stringWithFormat:@"%d",
                                                              game.houseCards[i]+1]]];
        [self.houseCards addObject:w];
        [self.view addSubview:w]; //We don't need to initialize it here because we do that in the updateHouseCards method
    }
    
    [self updateHouseCards];
    [self updateView];
    
    [self endRound];
    
}

- (IBAction)double_ {
 
    [game double_];
    [self hit];
    [self stand];

}

- (IBAction)split {
    

}

- (void)endRound {
    
    [game endRound];
    [self updateView];

    
}

- (IBAction)continue_ {
    
    //Remove the player and house cards
    for (int i = 0; i < game.currentHouseCards; i++) {
        [[self.houseCards objectAtIndex:0] removeFromSuperview];
        [self.houseCards removeObjectAtIndex:0];
    }
    
    for (int i = 0; i < game.currentPlayerCards; i++) {
        [[self.playerCards objectAtIndex:0] removeFromSuperview];
        [self.playerCards removeObjectAtIndex:0];
    }
    
    if (game.currentRound < game.rounds && game.currentChips > 0) { //Only continue if there's another round and we have enough chips
        [game newRound];
        [self updateView];
    } else {
        //End the game here
        //Push a results view and then quit
        UIAlertView* results = [[UIAlertView alloc] initWithTitle:@"Results" 
                                                          message:[NSString stringWithFormat:@"Rounds played: %d\nTotal profit: %d chip(s)\nProfit per round: %0.f chip(s)\n",game.currentRound,game.currentChips-game.chips,((float)(game.currentChips-game.chips))/game.currentRound] delegate:self cancelButtonTitle:@"Quit" otherButtonTitles:nil, nil];
        [results show];
        //[self.view addSubview:results];
    
    }
    
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex { 
    //Remove this view and go back to the title screen.
    [self.navigationController popToRootViewControllerAnimated:YES];
    
}

- (void)dealloc
{
    [super dealloc];
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

@end
